<?php
$GLOBALS['online'] = 0;
require_once('crontab_header.php');

set_time_limit(0);
// 凌晨4点到4点05分 脚本关闭
list($hour, $min, $second) = explode(':', date('H:i:s'));
$hour = intval($hour);
$min = intval($min);
if($hour==4 && $min==1 && $second<10){
    die;
}
if($GLOBALS['online']){
	define('APP_STORE_FILES_PATH', '/data/httpd/example.com/configs/wanlitong_prod_ck.pem');
	define('APP_STORE_FILES_PASS', 'pawlt888888');
	define('APP_STORE_SSL', 'ssl://gateway.push.apple.com:2195');
	define('APP_STORE_TIMEOUT', 30);
}else{
	define('APP_STORE_FILES_PATH', '/data/httpd/mobileappcms.wanlitong.com/configs/ck.pem');
	define('APP_STORE_FILES_PASS', '123456');
	define('APP_STORE_SSL', 'ssl://gateway.sandbox.push.apple.com:2195');
	define('APP_STORE_TIMEOUT', 30);
}
log_file('---begin---');
while (true) {
	$t1 = microtime_float();
	$device_id_arr = array();
	$now = date('Y-m-d H:i:s');
	$sql = "select pa_push_news_id,push_news_content,push_news_url,push_time from pa_push_news where push_news_timeout>'$now' and push_flag=1 order by pa_push_news_id desc limit 1";
	$news_arr = model_base::DB() -> query($sql) -> fetch();
  	if(empty($news_arr)){
  		$t2 = microtime_float();
		$t = ($t2-$t1)*1000000+500000;
		$t = $t>2000000?2000000:$t;
		usleep($t);
  		continue;	
  	}
  	$news_id= $news_arr['pa_push_news_id'];
	$news_content = mb_substr($news_arr['push_news_content'], 0, 140, 'utf-8');
  	$news_link = $news_arr['push_news_url'];
  	$news_push_time = $news_arr['push_time'];
  	
  	$sql = "select count(*) as count from pa_device_token where last_news_id<>$news_id and raw_add_time<'$news_push_time'";
	$row = model_base::DB() -> query($sql) -> fetch();
    $clientCount = $row['count'];
    if($clientCount<=0){
    	$t2 = microtime_float();
		$t = ($t2-$t1)*1000000+500000;
		$t = $t>2000000?2000000:$t;
		usleep($t);
    	continue;
    } 
    
	$size = 5;
	$total_page = ceil($clientCount/$size);
	for ($page=1;$page<=$total_page;$page++){
		$t3 = microtime_float();
		$ctx = stream_context_create();
        stream_context_set_option($ctx, 'ssl', 'local_cert', APP_STORE_FILES_PATH);
        stream_context_set_option($ctx, 'ssl', 'passphrase', APP_STORE_FILES_PASS);
        
        $begin = ($page-1) * $size;
        $sql = "select device_token_id,device_token,news_unread from pa_device_token where last_news_id<>$news_id and raw_add_time<'$news_push_time' limit $begin,$size ";

        $getClientData = model_base::DB() -> query($sql) -> fetchAll();
        $device_ids = '';
		if (!empty($getClientData)) {
            foreach ($getClientData as $v) {
            	$fp = stream_socket_client(APP_STORE_SSL, $err, $errstr, APP_STORE_TIMEOUT, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
		        if ($fp === FALSE){
		        	log_file("Failed to connect: $err " . iconv("GBK", "UTF-8", $errstr));
		        }
            	$device_ids .= $v['device_token_id'].',';
            	$new_unread = $v['news_unread']+1;
                $body = array();
                $body['aps'] = array(
                    'alert' => ':alert',
                    'sound' => 'default',
                    'link' =>$news_link ,
                    'badge' => $new_unread,
                );
                $payload = json_encode($body);
                $payload = str_replace(':alert', $news_content, $payload);
                $deviceToken = $v['device_token'];
                $msg = chr(0) . pack('n', 32) . pack('H*', $v['device_token']) . pack('n', strlen($payload)) . $payload;
                $result = fwrite($fp, $msg, strlen($msg));
                if (!$result)
                    log_file("Message not delivered: $deviceToken , body:$payload");
                else
                    log_file("Message successfully delivered: $deviceToken , body:$payload");
        		fclose($fp);
            }
            //更新news_id
            $device_ids = trim($device_ids,',');
            $sql = "update pa_device_token set last_news_id=$news_id,news_unread=news_unread+1 where device_token_id in ($device_ids)";
            model_base::DB() -> query($sql);
        }
        
        $t4 = microtime_float();
		$t = ($t4-$t3)*1000000+500000;
		$t = $t>2000000?2000000:$t;
		usleep($t);
	}
  	
  	$t2 = microtime_float();
	$t = ($t2-$t1)*1000000+500000;
	$t = $t>2000000?2000000:$t;
	usleep($t);
}

log_file('---end---');

function log_file($str,$force=false,$file='/tmp/levsion/push/push_news.log')
{
	if(!$force)
	return true;
	$t = microtime_float();
	$_log_file = $file;
	if (is_array($str)) {
		$str = "--- print array ---\n".var_export($str, true);
	}
	$str = '['.date("m-d H:i:s").'] '.$t.' '.$str."\n";
	error_log($str, 3, $_log_file);
}
function microtime_float() {
   list($usec, $sec) = explode(" ", microtime());
   return ((float)$usec + (float)$sec);
}